<?php
/**
 * 把email导入db  
 *
 * @filesource dump.php
 * @package ccmail 
 * @subpackage 
 * @version $id: 0.1, utf8, Fri Feb  4 12:16:05 CST 2011$
 * @author LD King <kldscs[at]gmail.com>
 * @copyright Copyleft (D.) 2007 - 2011 LD pr.
 * @link 
 * @example 
 *   
 */

require_once 'startup.php';

define('CCDIR', dirname(__FILE__).'/fish/' );
define('CCBKDIR', dirname(__FILE__).'/backup/' );

//$db  = _db::object();
//var_dump($db);


//exit('jijiu');
ccmail_dir(CCDIR, true);


//循环文本目录
function ccmail_dir($dir, $is_digg=false){

    if(is_dir( $dir ) == false) {
        die('no dir: '. $dir);
    }

    if(is_readable( $dir) === false){
        die('no readable: '. $dir);
    }

    $files = scandir( $dir );
    foreach($files as $file){
        if(strpos($file, '.') === 0) {
            echo " none file: {$file} \t\n"; 
            continue;
        }
        
        $file = $dir . $file;
        if(is_dir($file) == true) {
            echo " dir file: {$file} \t\n";
            if(true==$is_digg){ //仅支持两级目录
                ccmail_dir($file.'/', false);
            }
            continue;
        }
        
        if(is_readable($file) == false) {
            echo   " unreadable:  {$file} \t\n";
            continue;
        }

        ccmail_file2($file);  //处理文件
        unlink($file); 
    }
    if(false==$is_digg){ //删除无用目录
        rmdir($dir);
    }

    echo "Fine !!\t\n";

}//END func ccmail_dir

//使用读全文件, 单个文件存入数据库
function ccmail_file2($filesrc){
    $rows = file_get_contents($filesrc);
    $rows = explode("\n", $rows);
    $ext = pathinfo($filesrc,PATHINFO_EXTENSION);

    echo "  file start: {$filesrc} \t\n";
    //Output a line of the file until the end is reached
    foreach($rows as $row)
    {
        $row = trim($row);
        $row = strtolower($row);
        echo "   read row:{$row};\t\n\n";
        if('csv'==$ext){
            ccmail_csvrow($row);
        }else{
            ccmail_txtrow($row);
        }
    }

    echo "  file ended: {$filesrc} \t\n";
}//END func ccmail_file2


//单个文件存入数据库
function ccmail_file($filesrc){
    $file = fopen($filesrc, "r") or exit("Unable to open file!");
    $ext = pathinfo($filesrc,PATHINFO_EXTENSION);

    echo "  file start: {$filesrc} \t\n";
    //Output a line of the file until the end is reached
    while(!feof($file))
    {
        $row = fgets($file);
        $row = trim($row);
        $row = strtolower($row);
        if('csv'==$ext){
            ccmail_csvrow($row);
        }else{
            ccmail_txtrow($row);
        }
    }
    fclose($file);

    echo "  file ended: {$filesrc} \t\n";
}//END func ccmail_file

function ccmail_txtrow($row){
    $mail = is_email_address($row, true);
    if(false==$mail){
        return false;
    }

    //$is_available = ccmail_hostcheck($mail['host']);
    $is_available = 1 ;
    
    $dbtable = new _dbtable('ccmail');
    $v = array('email'=>$mail['email'],
        'host'=>$mail['host'],
        'is_available' => (int)$is_available,
        'updated'=>time(),
    ); 
    $one = $dbtable->fetchRow(array('email'=>$mail['email']));
    if( empty($one)){
        $id = $dbtable -> insert($v);
        echo "  ==> {$mail['email']}({$id}) \t\n";

    }elseif( (int)$is_available != $one['is_available']){
        $dbtable->update($v, array('object_id'=>$one['object_id']));
        echo "  ++> {$mail['email']}({$one['object_id']}) \t\n";
    }

}//END func  ccmail_txtrow

function ccmail_csvrow($row){
    $row = explode(',', $row);
    if(empty($row[1])){
        return false;
    }
    $mail = is_email_address($row[1], true);
    if(false==$mail){
        return false;
    }

    //$is_available = ccmail_hostcheck($mail['host']);
    $is_available = 1 ;
    
    $dbtable = new _dbtable('ccmail');
    $v = array('email'=>$mail['email'],
        'host'=>$mail['host'],
        'is_available' => (int)$is_available,
        'updated'=>time(),
        'name' => $row[0],
        'phone' => $row[2],
    );
    if( !empty($row[3])){
        $v['extra'] = json_encode(array('rmb'=>$row[3]));
    }

    $one = $dbtable->fetchRow(array('email'=>$mail['email']));
    if( empty($one)){
        $id = $dbtable -> insert($v);
        echo "  ==> {$mail['email']}({$id}) \t\n";

    }elseif( (int)$is_available!=$one['is_available']  
     || $v['name']!=$one['name']  ){
        $dbtable->update($v, array('object_id'=>$one['object_id']));
        echo "  ++> {$mail['email']}({$one['object_id']}) \t\n";
    }

}//END func ccmail_csvrow

//邮件域是否可用检查
function ccmail_hostcheck($host){
    $cache_obj = _cache::object();
    
    $arr_enable = $cache_obj -> get('arr_enable');
    if( !is_array($arr_enable)){
        $arr_enable = array(); //可用host
        $cache_obj->set('arr_enable', $arr_enable);
    }

    if( array_key_exists($host, $arr_enable) ){
        return $arr_enable[$host];
    }

    echo "   gethostbyname: {$host}\t\n";
    $h = gethostbyname($host);
    if(false!==stripos($host, $h)){
        $h = true;
    }else{
        $h= false;
    }
    $arr_enable[$host] = $h;

    $cache_obj->set('arr_enable', $arr_enable);
    return $h;
}//END func ccmail_hostcheck


/**
 * 验证是否是合法的email地址
 *
 * @param string $mail
 * @return boolean
 */
function is_email_address($mail, $is_return=false) { //[valid_email_address]
    $user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
    $domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
    $ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
    $ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';

    $return =  preg_match("/^$user@($domain|(\[($ipv4|$ipv6)\]))$/", $mail, $m);
    $return = (0<$return);
    if(false==$is_return){
        return $return;
    }

    if(false==$return){
        return false;
    }
    else{
        $result = array('email'=>array_shift($m), 'host'=>array_pop($m));
        if( 32<strlen($result['email']) ){
            return false;
        }else{
            echo "   find mail:<{$result['email']}>\t\n";
            return $result;
        }
    }

}//END func is_email_address



